package com.huangkailong.gitimgbed.view;

import cn.hutool.core.swing.clipboard.ClipboardUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.inject.Inject;
import com.huangkailong.gitimgbed.core.ImgBedConfiguration;
import com.huangkailong.gitimgbed.core.ViewDispatcher;
import com.huangkailong.gitimgbed.service.ImgBedService;
import com.huangkailong.gitimgbed.util.ToastUtil;
import com.huangkailong.gitimgbed.viewmodel.MainViewModel;
import de.saxsys.mvvmfx.FxmlView;
import de.saxsys.mvvmfx.InjectViewModel;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * @author huangkl
 * @since 1.0.0
 */
@Slf4j
public class MainView implements FxmlView<MainViewModel>, Initializable {
    @FXML
    private VBox vBoxRoot;
    @FXML
    private TextField textFieldImgUrl;
    @FXML
    private AnchorPane anchorPaneProgress;
    @InjectViewModel
    private MainViewModel mainViewModel;
    @Inject
    private ImgBedService imgBedService;
    @Inject
    private ImgBedConfiguration imgBedConfiguration;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        textFieldImgUrl.textProperty().bind(mainViewModel.imgUrlProperty());
    }

    public void handleOpenMenuItem(ActionEvent e){
        doUpload();
    }

    public void handleQuitMenuItem(ActionEvent e){
        ViewDispatcher.closeView(MainView.class);
        System.exit(0);
    }

    public void handleConfig(ActionEvent e){
        ViewDispatcher.showView(SettingView.class);
    }

    @FXML
    public void handleUploadButton(ActionEvent e){
        doUpload();
    }

    @FXML
    public void handleCopyButton(ActionEvent e){
        final String text = textFieldImgUrl.getText();
        if(StrUtil.isBlank(text)){
            ToastUtil.toast("数据为空，无法复制！");
        }else {
            ClipboardUtil.set(new StringSelection(text));
            ToastUtil.toast("复制成功！");
        }
    }

    @FXML
    public void handleClipboardButton(ActionEvent e){
        final Image image = ClipboardUtil.getImage();
        if(Objects.isNull(image)){
            ToastUtil.toast("剪贴板没有图片！");
            return;
        }

        try {
            final File file = saveImage(image);
            addFile(file);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void doUpload() {
        FileChooser fileChooser = createFileChooser();
        final File file = fileChooser.showOpenDialog(getWindow());
        Optional.ofNullable(file).ifPresent(this::addFile);
    }

    private File saveImage(Image image) throws IOException {
        final String tmpDir = System.getProperty("java.io.tmpdir");
        final File file = new File(tmpDir, IdUtil.simpleUUID() + ".png");
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(image, null, null);
        ImageIO.write(bufferedImage, "png", file);
        return file;
    }

    private void addFile(File f) {
        anchorPaneProgress.setVisible(true);
        ThreadUtil.execute(()->{
            try {
                final String url = imgBedService.uploadImg(f);
                mainViewModel.setImgUrl(url);
                anchorPaneProgress.setVisible(false);
            }catch (Exception exception) {
                anchorPaneProgress.setVisible(false);
                log.error(exception.getMessage(), exception);
                ToastUtil.toast(exception.getMessage());
            }
        });
    }

    private FileChooser createFileChooser() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择需要上传的文件");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG", "*.png"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                new FileChooser.ExtensionFilter("JPEG", "*.jpeg"),
                new FileChooser.ExtensionFilter("GIF", "*.gif"));
        return fileChooser;
    }

    private Window getWindow() {
        return vBoxRoot.getScene().getWindow();
    }
}
